package rlyy.framework.netty.support;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.CharsetUtil;
import org.apache.logging.log4j.util.Strings;
import rlyy.framework.core.common.enums.APIKey_Enum;
import rlyy.framework.core.common.request.FullRequest;
import rlyy.framework.core.common.utils.CommonUtil;
import rlyy.framework.core.maping.RequestHandlerMapping;

import java.util.Optional;

/**
 * 默认的json参数转换对象参数
 *
 * @author yuanqinglong
 * @since 2021/4/14 10:28
 */

public class DefaultParameterConversion {


    public static FullRequest conversion(FullHttpRequest fullHttpRequest) {
        String content = fullHttpRequest.content().toString(CharsetUtil.UTF_8);
        //解析内容
        JSONObject param = JSONObject.parseObject(content, Feature.OrderedField);
        CommonUtil.checkParamsIntegrity(param);
        //执行方法
        String api = param.getString(APIKey_Enum.API.getKey());
        api = Optional.ofNullable(Strings.trimToNull(api)).orElseGet(() -> RequestHandlerMapping.convertUri(fullHttpRequest.uri()));
        FullRequest fullRequestBody = param.toJavaObject(FullRequest.class);
        fullRequestBody.setApi(api);
        return fullRequestBody;
    }



}
